package tc.crase.view;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import tc.common.registry.Filter;
import tc.common.registry.Obj;
import tc.crase.db.Xattr;
import tc.crase.db.Xdb;
import tc.crase.db.Xobject;
import tc.crase.sys.XobjectEx;

public class FilterXobject implements Filter{
	Xdb    xdb;
	String filterType;
	String filterContentRegexp;
	boolean graph;
	String filterAttrName;
	
	public FilterXobject(Xdb xdb, String filterType, String filterAttrName, String filterContentRegexp, boolean graph) {
		this.xdb                 = xdb;
		this.filterType          = filterType;
		this.filterContentRegexp = filterContentRegexp;
		this.graph               = graph;
		this.filterAttrName      = filterAttrName;
	}
	
	public boolean pass(Obj obj) {
		if (obj instanceof XobjectEx.ObjEx == false) return false;
		
		XobjectEx.ObjEx objEx = (XobjectEx.ObjEx)obj;
		if ( objEx.getObject().getDb() != xdb ) return false; 

		if (filterAttrName.isEmpty() == false) {
			boolean isAttrName = false; 
			
			for (Xattr attr : objEx.getObject()) {
				if (filterAttrName.equals(attr.getName()) == false) continue;
				isAttrName = true;
				break;
			}
			
			if (isAttrName == false) return false;
		}
		
		if (graph) {
			boolean isGraph = false;
			
			for (Xattr attr : objEx.getObject()) {
				if (attr.getAsGRP() == null) continue;
				isGraph = true;
				break;
			}
			
			if (isGraph == false) return false;
		}
		
		boolean filterTypeOk    = filterType.isEmpty()    ? true : false;
		boolean filterContentOk = filterContentRegexp.isEmpty() ? true : false;
				
		if ( filterTypeOk && filterContentOk ) return true;
		
		for (Xattr attr : objEx.getObject()) {
			//Xattr attr = attrs.get(i);
			
			if ( (attr.getAsTPE() != null) && (filterTypeOk == false) ) {
				if (filterType.equals(attr.getAsTPE().id)) filterTypeOk = true;
			}
			else if ( ( (attr.getAsSTR() != null) || (attr.getAsURL() != null) ) && 
					                (filterContentOk == false) ) {
				Pattern p = Pattern.compile(filterContentRegexp, Pattern.CASE_INSENSITIVE);
				Matcher m = p.matcher(attr.getValue());
				if ( m.find() ) 
				{	filterContentOk = true;
				}
			}
			
			if ( filterTypeOk && filterContentOk ) return true;
		}
		
		return false;

	}
}
